﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore.Diagnostics;
using SlaughterItem.Common.Domains.Log;
using SlaughterItem.Common.Dtos;
using SlaughterItem.Common.Infrastructures.Interfaces;
using SlaughterItem.Enum;

namespace SlaughterItem.API.Application.Commands.Week02.Log
{
    public class AddLogDataHandler : IRequestHandler<AddLogDataCommand, Result>
    {
        public AddLogDataHandler(IBaseRepository<LogData> logDataRepository, IMapper mapper)
        {
            LogDataRepository = logDataRepository;
            this.mapper = mapper;
        }

        public IBaseRepository<LogData> LogDataRepository { get; set; }
        public IMapper mapper { get; set; }
        public async Task<Result> Handle(AddLogDataCommand request, CancellationToken cancellationToken)
        {
            var result=new Result() { Code=(int)CommonErrorCode.Added};
            var GetNum = LogDataRepository.GetAll().Where(x => x.LogDatas == request.LogDatas).Count();
            if (GetNum > 0)
            {
                return result;
            }
            else
            {
                var LogData = mapper.Map<LogData>(request);
                var list = LogDataRepository.Add(LogData);
                if (list > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    return result;
                }
                else
                {
                    return result;
                }
            }
        }
    }
}
